import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }

}
@WebServlet("/confession_wall")
public class Confession_Wall extends HttpServlet {
    private ObjectMapper mapper=new ObjectMapper();
    private List<Message> list=new LinkedList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 其保存的作用，将 req 请求解析，并存储 起来

        Message m=mapper.readValue(req.getInputStream(),Message.class);

        System.out.println("收到的数据 ： " +m);

        list.add(m);

        resp.setStatus(200);
        resp.getWriter().write("ok");

    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 当网页加载时，首先会发送一个 get 请求，我们这里就是在处理 get 请求
        // 首先返回一个 200 ok
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        //resp.getWriter().write("ok");
        // 将 数组中的数据 存储到 list 中
        String respJson=mapper.writeValueAsString(list);
        //String respJson=mapper.writeValueAsString(req);

        System.out.println(respJson.toString());
        resp.getWriter().write(respJson);

    }
}